<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<script type="text/javascript">
	window.onload = function (){
		var oUsername = document.getElementById('username');
		var oLogin = document.getElementById('login');
		var oDel = document.getElementById('del');

		if ( getCookie('用户名称') ) {
			oUsername.value = getCookie('用户名称')
		};

		oLogin.onclick = function (){
			alert('登陆成功');
			setCookie('用户名称', oUsername.value, 5)
		}

		oDel.onclick = function (){
			var re = confirm('确定要删除cookie吗？');
			
			if (re) {	
				removeCookie('用户名称');
				oUsername.value = '';
			};

			return re;
		}
	}
	//设置 + 获取 + 清除
	function setCookie(key, value, t){
		var oDate = new Date();
		oDate.setDate( oDate.getDate() + t );

		document.cookie = key + '=' + encodeURI(value)+';expires=' + oDate.toGMTString();
	}

	function getCookie(key){
		var arr1 = document.cookie.split('; ');
		//alert(arr1)								//arr1=[username=leo,age=32]
		for (var i = 0; i < arr1.length; i++) {
			var arr2 = arr1[i].split('=');
			//alert(arr2)							//arr2=[ [username,leo],[age,32] ]
			//alert(arr2.length)					//2 && 2
			//alert(arr2[0])						//username && age
			if ( arr2[0]==key ) {
				return decodeURI( arr2[1] );
			};
		};
	}

	function removeCookie(key){
		setCookie(key, '', -1)
	}
	</script>
</head>
<body>
	<input id="username" type="text" />
	<input id="login" type="button" value="登陆" />
	<input id="del" type="button" value="删除" />
</body>
</html>